import pako from "pako";
import atob from "atob";
import btoa from "btoa";


export default {
  getFundDetail(id) {
    if (!id) { return Promise.resolve().then(() => { }); }
    let detail = callTaoba('/idols/detail', { "id": id, "requestTime": new Date().getTime(), "pf": "h5" })
    let rank = callTaoba('/idols/join/rank', { "id": id, "requestTime": new Date().getTime(), "pf": "h5", 'iscoopen': 0, '_version_': 1, })
    return Promise.all([detail, rank]).then(res => {
      let detail = res[0];
      let rank = res[1];
      return {
        raised: detail.datas.donation,
        backers: rank.juser,
      }
    })
  }
};


const headers = {
  "content-type": "application/json",
  'Host': 'www.taoba.club',
  'Referer': 'https://www.taoba.club/',
  'Origin': 'https://www.taoba.club',
  Accept:
    "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}

function callTaoba(path, params) {
  return fetch('https://www.taoba.club' + path, {
    body: encodeBody(JSON.stringify(params)), // must match 'Content-Type' header
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    headers: headers,
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, cors, *same-origin
    redirect: "follow", // manual, *follow, error
    // referrer: "no-referrer" // *client, no-referrer
  }).then(res => res.text()).then(decodeBody).then(JSON.parse);
}

function encodeBody(str) {
  let len = str.length
  let comprressed = pako.deflate(stringToUint8Array(str))
  let salted = salt(comprressed)
  let rst = btoa(Uint8ArrayToString(salted))
  return len + '$' + rst
}

function decodeBody(rsp) {
  let src = rsp.split('$')[1]
  let salted = stringToUint8Array(atob(src))
  let comprressed = salt(salted)
  return Uint8ArrayToString(pako.inflate(comprressed))
}

function salt(data) {
  let ori = data.slice()
  let salt = stringToUint8Array('%#54$^%&SDF^A*52#@7');
  for (let i = 0; i < data.length; i++) {
    if (i % 2 == 0) {
      let ch = ori[i] ^ salt[i / 2 % salt.length];
      ori[i] = ch;
    }
  }
  return ori
}

function Uint8ArrayToString(fileData) {
  let dataString = "";
  for (let i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i]);
  }
  return dataString
}

function stringToUint8Array(str) {
  let arr = [];
  for (let i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
  let tmpUint8Array = new Uint8Array(arr);
  return tmpUint8Array
}
